/**
 * User Slice - 用户状态切片
 * 
 * 负责管理用户相关的全局状态:
 * - 用户信息
 * - 权限列表
 * - 登录状态
 * - 令牌管理
 */
import { createSlice, createAsyncThunk, PayloadAction } from '@reduxjs/toolkit';
import { AppDispatch, RootState } from '../index';
import type { User } from '../../types';
import auth from '../../utils/auth'; // 直接导入auth

// 用户状态接口
interface UserState {
  userInfo: User | null;
  token: string | null;
  isLoading: boolean;
  error: string | null;
  rights: string[];
  initialized: boolean; // 新增状态标记，防止重复初始化
}

// 初始状态 - 不依赖auth工具的基础值
const initialState: UserState = {
  userInfo: null,
  token: null,
  isLoading: false,
  error: null,
  rights: [],
  initialized: false
};

// 异步获取用户权限
export const fetchUserRights = createAsyncThunk<
  string[], // 返回类型
  void,     // 参数类型
  { rejectValue: string } // 错误类型
>(
  'user/fetchUserRights',
  async (_, { rejectWithValue, getState }) => {
    try {
      // 检查权限是否已经加载
      const state = getState() as RootState;
      if (state.user.rights.length > 0) {
        return state.user.rights;
      }
      
      // 模拟权限API请求
      await new Promise(resolve => setTimeout(resolve, 300));
      
      // 从本地存储获取权限
      const storedRights = auth.getUserRights();
      
      // 如果有已保存的权限，直接返回
      if (storedRights && storedRights.length > 0) {
        // 减少日志输出
        return storedRights;
      }
      
      // 获取用户信息
      const userInfo = auth.getUserInfo();
      
      // 如果用户信息中有权限，返回这些权限
      if (userInfo?.role?.rights && Array.isArray(userInfo.role.rights)) {
        // 减少日志输出
        return userInfo.role.rights;
    }
      
      // 如果都没有，返回基于角色的默认权限
      const roleId = userInfo?.role?.id || userInfo?.roleId || '3'; // 默认为编辑角色
      
      // 将可能的字符串ID转为数字
      const roleIdNum = typeof roleId === 'string' ? parseInt(roleId, 10) : roleId;
      
      return generateDefaultRights(roleIdNum, userInfo);
    } catch (error) {
      return rejectWithValue('获取用户权限失败');
  } 
  },
  {
    // 条件执行，防止重复请求
    condition: (_, { getState }) => {
      const state = getState() as RootState;
      // 如果已经在加载或已初始化，则不再执行
      return !state.user.isLoading && !state.user.initialized;
    }
  }
);


// 生成默认权限
const generateDefaultRights = (roleId: number, user: User | null): string[] => {
  const rights: string[] = [];
    
  // 根据角色ID生成不同的默认权限
  if (roleId === 1) {
    // 超级管理员权限
    rights.push(
      '/home',
      '/user-manage',
        '/user-manage/list',
      '/right-manage',
        '/right-manage/role/list',
        '/right-manage/right/list',
      '/news-manage',
        '/news-manage/add',
        '/news-manage/draft',
        '/news-manage/category',
      '/audit-manage',
        '/audit-manage/audit',
        '/audit-manage/list',
      '/publish-manage',
        '/publish-manage/unpublished',
        '/publish-manage/published',
      '/publish-manage/sunset'
    );
  } else if (roleId === 2) {
      // 管理员权限
      rights.push(
      '/home',
      '/news-manage',
        '/news-manage/add',
        '/news-manage/draft',
        '/news-manage/category',
        '/audit-manage/audit',
        '/audit-manage/list'
      );
    } else {
      // 编辑最低权限
      rights.push(
        '/news-manage/add',
        '/news-manage/draft'
      );
  }
  
  // 确保首页访问权限
  if (!rights.includes('/home')) {
    rights.push('/home');
  }
  
  // 使用auth工具缓存权限列表
  auth.setUserRights(rights);
  
  return rights;
};

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    setUser: (state, action: PayloadAction<User>) => {
      state.userInfo = action.payload;
      state.isLoading = false;
      state.error = null;
      state.initialized = true;
      
      // 确保从用户对象中获取权限，但避免不必要的console.log
      if (action.payload.role?.rights && Array.isArray(action.payload.role.rights)) {
        state.rights = action.payload.role.rights;
        
        // 避免在userSlice中直接调用auth.setUserInfo，防止循环调用
        // 此处只更新Redux状态，auth中的用户信息由调用方负责更新
      }
    },
    setUserInfo: (state, action: PayloadAction<User>) => {
      state.userInfo = action.payload;
      state.isLoading = false;
      state.error = null;
      state.initialized = true;
      
      // 避免在userSlice中直接调用auth.setUserInfo，防止循环调用
    },
    setToken: (state, action: PayloadAction<string | null>) => {
      state.token = action.payload;
      
      // 避免在userSlice中直接调用auth.setToken，防止循环调用
      // 调用方负责更新localStorage
      
      // 清除token时重置初始化状态
      if (!action.payload) {
        state.initialized = false;
        }
    },
    setLoading: (state, action: PayloadAction<boolean>) => {
      state.isLoading = action.payload;
    },
    setRights: (state, action: PayloadAction<string[]>) => {
      state.rights = action.payload;
      
      // 避免在userSlice中直接调用auth.setUserRights，防止循环调用
    },
    clearUser: (state) => {
      state.userInfo = null;
      state.token = null;
      state.isLoading = false;
      state.rights = [];
      state.initialized = false;
      
      // 避免在userSlice中直接调用auth.clearUserInfo，防止循环调用
    },
    setError: (state, action: PayloadAction<string | null>) => {
      state.error = action.payload;
    }
  },
  extraReducers: (builder) => {
    // 处理fetchUserRights异步action
    builder.addCase(fetchUserRights.pending, (state) => {
      state.isLoading = true;
    });
    builder.addCase(fetchUserRights.fulfilled, (state, action) => {
      state.rights = action.payload as string[];
      state.isLoading = false;
      state.initialized = true;
      
      // 直接使用auth工具保存权限
        auth.setUserRights(action.payload as string[]);
        
        // 如果已有用户信息，同步更新用户对象中的权限
        if (state.userInfo && state.userInfo.role) {
          state.userInfo.role.rights = action.payload as string[];
        }
    });
    builder.addCase(fetchUserRights.rejected, (state, action) => {
      state.isLoading = false;
      state.error = action.payload as string;
    });
  }
});

// 导出actions
export const { 
  setUser, 
  setUserInfo, 
  setToken,
  setLoading, 
  setRights, 
  clearUser, 
  setError 
} = userSlice.actions;

// 创建初始化action，在应用启动时调用
export const initializeUserState = () => async (dispatch: AppDispatch, getState: () => RootState) => {
  // 检查是否已初始化
  const state = getState();
  if (state.user.initialized) {
    return;
  }
  
  try {
    // 获取缓存的用户信息
    const userInfo = auth.getUserInfo();
    const token = auth.getToken();
    
    if (userInfo && token) {
      // 设置用户信息和token
      dispatch(setUser(userInfo));
      dispatch(setToken(token));
    
      // 获取权限
      dispatch(fetchUserRights());
    }
  } catch (error) {
    console.error('初始化用户状态失败:', error);
  }
};

// 选择器函数
export const selectUserInfo = (state: RootState) => state.user.userInfo;
export const selectToken = (state: RootState) => state.user.token;
export const selectUserLoading = (state: RootState) => state.user.isLoading;
export const selectUserError = (state: RootState) => state.user.error;
export const selectUserRights = (state: RootState) => state.user.rights;

// 权限检查函数
export const selectHasPermission = (permissionKey: string) => async () => {
  return auth.hasPermission(permissionKey);
};

export default userSlice.reducer;

 